package com.fbox;
import java.io.IOException;
import java.net.Proxy;

import microsoft.aspnet.signalr.client.hubs.HubProxy;
import redis.clients.jedis.Jedis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boilerCloud.util.MD5;
import com.boilerCloud.util.RedisPoolsUtil;
import com.fbox.models.BoxStateChanged;
import com.fbox.signalr.SignalRConnectionBase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class FBoxSignalRConnection extends SignalRConnectionBase {

    private final Gson gson;
    private final com.fbox.Logger logger;
    private Proxy proxy;

    public FBoxSignalRConnection(String hubUrl, String signalrClientId, TokenManager tokenManager, Proxy proxy, LoggerFactory loggerFactory) {
        super(hubUrl, signalrClientId, tokenManager, proxy, loggerFactory);
        this.logger = loggerFactory.createLogger("FBoxSignalRConnection");
        this.proxy = proxy;
        gson = new GsonBuilder().create();
    }

    @Override
    protected void onHubProxyCreated(HubProxy hubProxy) {
        hubProxy.subscribe("dmonUpdateValue").addReceivedHandler(jsonElements -> {
        	//System.out.println(jsonElements);
        	System.out.println("dmon data received: ");
        	Jedis jedis = RedisPoolsUtil.getInstance().getResource();
        	
            Global.threadPool.submit(() -> {
	        	System.out.println("------===");                          
	        	String boxid = jsonElements[2].toString();
	        	boxid = boxid.substring(1, boxid.length()-1);
	        	String key = "boxid_" + boxid;
	        	System.out.println("key"+key);
	        	JSONArray jsonArray = JSONArray.parseArray(jsonElements[1].toString());
	        	JSONObject json = new JSONObject();
	        	if(jedis.get(key) != null){
	        		 json = JSONObject.parseObject(jedis.get(key));
	        	}
	        	String value ="";
	        	for (int i = 0; i < jsonArray.size(); i++) {
	        		value = jsonArray.getJSONObject(i).getString("name") +"_" + jsonArray.getJSONObject(i).getString("value");
	        		json.put(MD5.md5(jsonArray.getJSONObject(i).getString("name")), value);
				}
	        	System.out.println("5555"+json);
	        	System.out.println("------------------------------");
	        	jedis.set(key, json.toJSONString());
	        	for (com.google.gson.JsonElement jsonElement : jsonElements) {
	        		//jsonElements[1];
	        		System.out.println (jsonElement + "-----------");
	        		
	        	}
            });
        	jedis.close();
        });

        hubProxy.subscribe("boxConnStateChanged").addReceivedHandler(jsonElements -> {
            Global.threadPool.submit(() -> {
                System.out.println("Box state changed.");
                if (jsonElements.length <= 0)
                    return;
                System.out.println(jsonElements.length);
                BoxStateChanged[] stateChanges = gson.fromJson(jsonElements[0], BoxStateChanged[].class);
                System.out.println("====="+stateChanges.length);
                for (BoxStateChanged stateChange : stateChanges) {
                    try {
                        Global.commServer.executePost("box/" + stateChange.id + "/dmon/start", String.class);
                        System.out.println("Start dmon points on box " + stateChange.id + " ok.");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        });
        
        hubProxy.subscribe("alarmTriggered").addReceivedHandler(jsonElements -> {
            Global.threadPool.submit(() -> {
                System.out.println("报警触发了");
                if (jsonElements.length <= 0)
                    return;
                for (com.google.gson.JsonElement jsonElement : jsonElements) {
	        		//jsonElements[1];
	        		System.out.println (jsonElement + "-----------");	        		
	        	}
            });
        });
        
        hubProxy.subscribe("alarmRecovered").addReceivedHandler(jsonElements -> {
            Global.threadPool.submit(() -> {
                System.out.println("报警触发了");
                if (jsonElements.length <= 0)
                    return;
                for (com.google.gson.JsonElement jsonElement : jsonElements) {
	        		//jsonElements[1];
	        		System.out.println (jsonElement + "-----------");	        		
	        	}
            });
        });
//            }

//            Global.threadPool.submit(() -> {
//                try {
//                    BoxGroup[] boxGroups = Global.appServer.executeGet("box/grouped", BoxGroup[].class);
//
//                    for (BoxGroup group : boxGroups) {
//                        for (BoxReg boxReg : group.boxRegs) {
//                            String boxNo = boxReg.box.boxNo;
//                            Global.commServer.executePost("dmon/start?boxNo=" + boxNo, String.class);
//                            System.out.println("Start dmon points on box " + boxNo + " ok.");
//                        }
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
    }
}
